<template>
  <div class="home-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>API 测试面板</h3>
        </div>
      </template>
      
      <el-space direction="vertical" size="large" style="width: 100%">
        <el-alert
          v-if="message"
          :type="message.type"
          :title="message.content"
          :closable="false"
          show-icon
        />

        <div class="api-test-section">
          <el-button type="primary" @click="testNormalApi" :loading="loading.normal">
            测试普通接口
          </el-button>
          <el-button type="warning" @click="testExpiredToken" :loading="loading.expired">
            测试Token过期
          </el-button>
        </div>

        <el-divider>请求结果</el-divider>

        <el-descriptions v-if="result" :column="1" border>
          <el-descriptions-item label="状态码">
            {{ result.status }}
          </el-descriptions-item>
          <el-descriptions-item label="响应数据">
            <pre>{{ JSON.stringify(result.data, null, 2) }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </el-space>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const message = ref(null)
const result = ref(null)
const loading = ref({
  normal: false,
  expired: false
})

const showMessage = (content, type = 'success') => {
  message.value = { content, type }
  setTimeout(() => {
    message.value = null
  }, 3000)
}

const testNormalApi = async () => {
  try {
    loading.value.normal = true
    const response = await axios.get('/api/protected')
    result.value = {
      status: response.status,
      data: response.data
    }
    showMessage('请求成功')
  } catch (error) {
    result.value = {
      status: error.response?.status || 500,
      data: error.response?.data || { message: '请求失败' }
    }
    showMessage(error.response?.data?.message || '请求失败', 'error')
  } finally {
    loading.value.normal = false
  }
}

const testExpiredToken = async () => {
  try {
    loading.value.expired = true
    const response = await axios.get('/api/test-expired')
    result.value = {
      status: response.status,
      data: response.data
    }
    showMessage('请求成功')
  } catch (error) {
    result.value = {
      status: error.response?.status || 500,
      data: error.response?.data || { message: '请求失败' }
    }
    showMessage(error.response?.data?.message || '请求失败', 'error')
  } finally {
    loading.value.expired = false
  }
}
</script>

<style scoped>
.home-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.api-test-section {
  display: flex;
  gap: 16px;
}

pre {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>